<template>
  <div>
    <nav-header></nav-header>
    <nav-bread>
      <span>Cart</span>
    </nav-bread>
    <div class="container">
      <div class="cart" v-if="cartList.length">
        <div class="page-title-normal">
          <h2 class="page-title-h2"><span>My Cart</span></h2>
        </div>
        <div class="item-list-wrap">
          <div class="cart-item">
            <div class="cart-item-head">
              <ul>
                <li>Items</li>
                <li>Price</li>
                <li>Quantity</li>
                <li>Subtotal</li>
                <li>Edit</li>
              </ul>
            </div>
            <ul class="cart-item-list">
              <li v-for="(item, index) in cartList" :key="index">
                <div class="cart-tab-1">
                  <div class="cart-item-check">
                    <a href="javascipt:;" class="checkbox-btn item-check-btn" :class="{ 'check': item.checked === '1'}"
                      @click="toggleItemCheck(item)">
                      <svg class="icon icon-ok">
                        <use xlink:href="#icon-ok"></use>
                      </svg>
                    </a>
                  </div>
                  <div class="cart-item-pic">
                    <img :src="`/static/${item.productImage}`" :alt="item.productName">
                  </div>
                  <div class="cart-item-title">
                    <div class="item-name">{{ item.productName }}</div>
                  </div>
                </div>
                <div class="cart-tab-2">
                  <div class="item-price">{{ item.salePrice | currency }}</div>
                </div>
                <div class="cart-tab-3">
                  <div class="item-quantity">
                    <div class="select-self select-self-open">
                      <div class="select-self-area">
                        <a class="input-sub" @click="alterItemNum(item, -1)">-</a>
                        <span class="select-ipt">{{ item.productNum }}</span>
                        <a class="input-add" @click="alterItemNum(item, 1)">+</a>
                      </div>
                    </div>
                  </div>
                </div>
                <div class="cart-tab-4">
                  <div class="item-price-total">{{ item.productNum * item.salePrice | currency }}</div>
                </div>
                <div class="cart-tab-5">
                  <div class="cart-item-opration">
                    <a href="javascript:;" class="item-edit-btn" @click="removeItemConfirm(item.productId)">
                      <svg class="icon icon-del">
                        <use xlink:href="#icon-del"></use>
                      </svg>
                    </a>
                  </div>
                </div>
              </li>
            </ul>
          </div>
        </div>
        <div class="cart-foot-wrap">
          <div class="cart-foot-inner">
            <div class="cart-foot-l">
              <div class="item-all-check">
                <a href="javascipt:;">
                  <span class="checkbox-btn item-check-btn"
                    :class="{'check': isAllChecked}"
                    @click="toggleAllCheck">
                      <svg class="icon icon-ok">
                        <use xlink:href="#icon-ok"></use>
                      </svg>
                  </span>
                  <span>Select all</span>
                </a>
              </div>
            </div>
            <div class="cart-foot-r">
              <div class="item-total">
                Item total: <span class="total-price">{{ totalPrice | currency }}</span>
              </div>
              <div class="btn-wrap">
                <a class="btn btn--red" :class="{'btn--dis': checkedCartList.length === 0}"
                  @click="checkout">Checkout</a>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div v-else class="cart-empty">购物车空空如也</div>
    </div>
    <nav-footer></nav-footer>
    <modal :showModal="showModalRemoveItem" @close="showModalRemoveItem = false">
      <p slot="message">确定要删除该商品吗？</p>
      <div slot="btnGroup">
        <button class="btn btn--m" @click="removeItem(toBeRemovedItemId)">确定</button>
        <button class="btn btn--m" @click="showModalRemoveItem = false">取消</button>
      </div>
    </modal>
  </div>
</template>
<script>
import '@/assets/css/checkout.css'
import NavHeader from '@/components/NavHeader'
import NavFooter from '@/components/NavFooter'
import NavBread from '@/components/NavBread'
import Modal from '@/components/Modal'
import axios from 'axios'
import store from '../store/store'
export default {
  name: 'Cart',
  components: {
    NavHeader,
    NavBread,
    NavFooter,
    Modal
  },
  data () {
    return {
      cartList: [],
      showModalRemoveItem: false,
      toBeRemovedItemId: ''
    }
  },
  computed: {
    // 用户选中的商品列表
    checkedCartList () {
      return this.cartList.filter(item => item.checked === '1')
    },
    isAllChecked () {
      return this.checkedCartList.length === this.cartList.length
    },
    totalPrice () {
      if (this.checkedCartList.length === 0) return '0'
      return this.checkedCartList.reduce((total, current) =>
        total + (parseInt(current.productNum) * parseFloat(current.salePrice)), 0)
    }
  },
  methods: {
    getCartList () {
      axios.get('/users/cart/cartList')
        .then(res => {
          if (res.status === 200) {
            const data = res.data
            this.cartList = data.result.list
          }
        })
    },
    // 弹出确认删除商品的模态框
    removeItemConfirm (productId) {
      this.toBeRemovedItemId = productId
      this.showModalRemoveItem = true
    },
    removeItem (productId) {
      this.showModalRemoveItem = false
      axios.post('/users/cart/removeItem', { productId })
        .then(res => {
          if (res.status === 200) {
            const data = res.data
            // 数据库删除商品成功
            if (data.status === '0') {
              console.log(`商品删除成功：${productId}`)
              // 删除的商品数量
              let n = this.cartList.find(item => item.productId === productId).productNum * -1
              store.setCartItemQuantityAction(n)
              // 将 vue 实例里的 data 删除相应商品条目
              this.cartList = this.cartList.filter(item => item.productId !== productId)
            }
          }
        })
    },
    // 修改商品数量，step 等于1即数量增1，step 等于-1即数量减1
    alterItemNum (item, step) {
      console.log('alter item number')
      // 首先在前端修改商品数量
      if (step === 1) {
        item.productNum++
        store.setCartItemQuantityAction(1)
      } else {
        if (item.productNum <= 1) {
          return
        }
        item.productNum--
        store.setCartItemQuantityAction(-1)
      }
      // 接着在后端操作数据库修改商品数量
      axios.post('/users/cart/alterItemNum', { productId: item.productId, productNum: item.productNum })
        .then(res => {
          if (res.status === 200) {
            const data = res.data
            if (data.status === '0') {
              // 数据库修改商品数量成功
              console.log(data.result)
            }
          }
        })
    },
    // 切换商品选中状态
    toggleItemCheck (item) {
      console.log('toggle item check state')
      item.checked = item.checked === '1' ? '0' : '1'
      axios.post('/users/cart/toggleItemCheck', { productId: item.productId, checked: item.checked })
        .then(res => {
          if (res.status === 200) {
            const data = res.data
            console.log(data)
          }
        })
    },
    // 全选/全不选切换
    toggleAllCheck () {
      let flag = !this.isAllChecked
      this.cartList.forEach(item => {
        item.checked = flag ? '1' : '0'
      })
      console.log('toggle all check')
      // 数据库操作
      axios.post('/users/cart/toggleAllCheck', { flag })
        .then(res => {
          if (res.status === 200) {
            const data = res.data
            console.log(data)
          }
        })
    },
    checkout () {
      if (this.checkedCartList.length === 0) return
      this.$router.push({ path: '/address' })
    }
  },
  mounted () {
    this.getCartList()
  }
}
</script>

<style>
  .input-sub,.input-add{
    min-width: 40px;
    height: 100%;
    border: 0;
    color: #605F5F;
    text-align: center;
    font-size: 16px;
    overflow: hidden;
    display: inline-block;
    background: #f0f0f0;
  }
  .item-quantity .select-self-area{
    background:none;
    border: 1px solid #f0f0f0;
  }
  .item-quantity .select-self-area .select-ipt{
    display: inline-block;
    padding:0 3px;
    width: 30px;
    min-width: 30px;
    text-align: center;
  }
  .cart-empty {
    text-align:center;
    font-size: 32px;
    padding: 20px 50px;
    min-height: 40vw;
  }
</style>
